-- show_hide_item
-- Created by chengb Mar/26/2016
-- 进入洞窟时可侦测隐藏物件

-- 隐藏物件的位置
local HIDE_POS_LIST = { 2, 4, 6, 10, 16, 20, 22, 24, };

return {
    apply = function(prop, baseValue)
        return tonumber(prop[3]);
    end,

    trigger = function(who, prop, arg)
        if not DungeonInstanceM.isInInstance() and
           not UnrealDungeonM.isInUnreal() then
            -- 不在副本或夹层迷宫中
            return;
        end

        local lastLayer = DungeonM.getDungeonMixedField("show_hide_item_layer");
        local curLayer = DungeonM.currentLayer();
        if lastLayer == curLayer then
            -- 本层已经出现过隐藏物件了
            return;
        end

        local emptyList = DungeonM.findEmptyGrids();
        local selectList = {};
        local pos;
        for _, pos in pairs(HIDE_POS_LIST) do
            -- 将空位加入到可选列表中
            if table.indexOf(emptyList, pos) ~= -1 then
                 table.insert(selectList, pos);
            end
        end

        if #selectList == 0 then
            -- 没有空位了
            return;
        end

        -- 随机挑选一个空位
        local rand = DungeonM.getRandSeed("show_hide_item") % #selectList;
        pos = selectList[rand + 1];

        -- 抽取隐藏物件
        local info = CaveHideItemM.fetchHideItem();
        local class = info.class;
        local element = info.element;
        if type(class) ~= "number" or type(element) ~= "number" then
            return;
        end

        local para = { ["class"] = class, ["element"] = element, };

        local msg = string.format("[show_hide_item]侦测到隐藏物件位置：%d", pos);
        DungeonLogM.addLog(msg);

        -- 执行转换
        DungeonM.transformGrid(class, pos, GRID_STATE_OPEN, para);

        -- 记录本层出现过隐藏物件
        DungeonM.setDungeonMixedField("show_hide_item_layer", curLayer);
    end,

    record = function(target, prop, path)
        local v = target.dbase:queryTemp("prop", path, {});
        table.insert(v, prop);
        target.dbase:setTemp("prop", path, v);

        return true;
    end
}